import Baby

class UController {
  def authenticateService
  def index = { }
  def edit = {

  }

  def show = {
    def p = authenticateService.userDomain()
    if(!p){
      redirect(controller:'login')
      return
    }
    def babies = Baby.findAllByPerson(p)
    if (babies.size() > 1) {
      render view: 'chosebaby', model: [babies: babies]
    } else if (babies.size() == 1) {
      def baby = babies[0]
      redirect(controller: "b", action: "show", id: baby.id)
    } else {
      def baby = new Baby()
      flash.message = 'You should finish your information.'
      render view: 'newbaby', model: [baby: baby]
    }
  }

  def newbaby = {
    def baby = new Baby()
    [baby: baby]
  }

  def savebaby = {
    def baby = new Baby()
    baby.properties = params
    def p = authenticateService.userDomain()
    def person = Person.get(p.id)
    baby.person = person
    if(params.stage){
      def stage = params.stage.toInteger()
      if(stage < 10000){
        person.stage  = 0
        person.save()
      } else if (stage < 20000) {
        baby.expectedBirth = baby.datePregnant + 280
      }
    }
    if (baby.save()) {
      redirect controller: 'b', action: 'show', id: baby.id
    } else {
      println baby.errors
      render view: 'edit', model: [baby: baby]
    }
  }


}
